import React, { Component } from 'react';
import { StyleSheet, Text, View, Image, ScrollView, TouchableOpacity, Dimensions, TextInput, Modal, ActivityIndicator } from "react-native";
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import { ProductEditing } from './_components/ProductEditing';
import Dictionary from '../../../utils/dictionary';
import ToastUtil from '../../../utils/toast';
import Upload from '../../../utils/Upload'
import navigationSeevice from '../../../components/navigation/navigationSeevice';
import { TabHeading } from 'native-base';
import ModalPicDelComponent from '../../../component/ModalPicDelComponent';


var ImagePicker = require('react-native-image-picker');

const ScreenWidth = Dimensions.get('window').width;
const ScreenHeight = Dimensions.get('window').height;
const scale = ScreenWidth / 375;
let selectIcon = require('../../../imgs/select.png');
let defaultImg = require('../../../imgs/addphoto.png');
let close = require('../../../imgs/global/error.png');

let imgOptions = {
  title: '请选择图片来源',
  cancelButtonTitle: '取消',
  takePhotoButtonTitle: '拍照',
  chooseFromLibraryButtonTitle: '相册图片',
  quality: 0.1,
  storageOptions: {
    skipBackup: true,
    path: 'images'
  }
};
const modalPicDelCfg = {
  visible: false,
  uri: null,
  delPress: () => { },
  picPress: () => { },
  fileId: '',
  delTextHide: true
}
export class newProject extends Component {
  static navigationOptions = ({ navigation }) => {
    return {
      title: '新增产品',
      headerTintColor: style.color.white,
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
      headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../imgs/goBackEmpty.png')} />),
      headerStyle: {
        elevation: 0,
        backgroundColor: style.color.themeColor,
      },
      headerTitleStyle: {
        flex: 1,
        textAlign: 'center'
      }
    }
  }

  constructor(props) {
    super(props);
    this.state = {
      goodsTreeList: [],
      submitVisible: false,
      modalVisible: false,
      mainMethodText: '请关联经营品类',
      mainObjectText: '请关联经营区域',
      mainTypeSelect: 0,
      modalObj: {
        currSelectIndex: -1,
        currTitle: '',
        currlistData: [],
        currCb: null,
        currIsVisible: false,
      },
      listData: [],
      imgServer: [],
      fileAddress: [],
      imgUrl: '',
      mainMethodTextCheck: [],
      loading: false,
      searching: false,
      showDataList:[

      ]
    };
    modalPicDelCfg.picPress = () => {
      modalPicDelCfg.visible = false;
      modalPicDelCfg.uri = null;
      this.setState({
          previewModalVisible: false,
      });
  }
    this.qualificationList = []
    this.companyId = props.navigation.state.params.companyId || '';
    this.choice = props.navigation.state.params.choice || {};
    this.pageFrom = props.navigation.state.params.pageFrom || '';
    this.params = {
      companyId: this.companyId,
      bizType: 'COMPANY_GOODS_INFO',
      goodsCateIdList: [],
      zone: '',
      fileAddress: '',
      comments: '',
      choice: this.choice,
      sourceFlag: this.pageFrom == 'RL' ? 1 : 0
    };
  }

  async	componentWillMount () {
    this._init();
  }

  //初始函数
  _init = async () => {
    this._getInitData();
    this._dictionaryFn();
  }

  async _getGoodsData (searchKey) {
    let responseData = await HTTP.POST(API_GENERATE(API.COMPANY_GOODS_ADD_LIST), { companyId: this.companyId, searchKey: searchKey.searchCode, corpId: this.choice.corpId });
    this.setState({ searching: false, goodsTreeList: responseData })
  }

  async _getInitData () {
    let responseData = await HTTP.POST(API_GENERATE(API.COMPANY_GOODS_ADD_LIST), { companyId: this.companyId, corpId: this.choice.corpId });
    this.setState({ goodsTreeList: responseData })
  }

  _getGoodsCode = (data) => {
    let mainMethodTextCheck = [];
    this.params.goodsCateIdList = [];
    this.dangetousTypeList = []
    for (var i = 0; i < data.length; i++) {
      const element = data[i].goodsList
      for (var j = 0; j < element.length; j++) {
        const subData = element[j]
        if (subData.select) {
          this.params.goodsCateIdList.push(subData.goodsCode);
          this.dangetousTypeList.push(subData.dangerousType);
          mainMethodTextCheck.push(subData.goodsName);
        }
      }
    }
    this.setState({ mainMethodTextCheck })
  }
  getQueInfo=async()=>{
    if(this.dangetousTypeList.length>0){
      let responseData = await HTTP.POST(API_GENERATE(API.QUERT_COMPANY_NEED_QUALIFI), {
        companyId: this.companyId, corpId: this.choice.corpId,dangetousTypeList:this.dangetousTypeList});
        if(responseData.length>0){
          let text = '本次新增品类涉及交易资质有：'
          responseData.map((item,index)=>{
            text += item.qualificationName
            if(item.isExpired == '-1'){
              text +='(已过期)'
            }
          else {
              if (item.isAuditing) {
                text +='(未认证)'
              } else {
                text +='(已认证)'
              }
            }
            if(index+1<responseData.length){
              text+='、'
            }
          })
          this.setState({
            text
          })
        }
        
    }
  }
  //获取状态数据字典
  _dictionaryFn = async () => {
    let listData = await Dictionary.get('EC_PRICE_REGION');

    this.setState({ listData })
  }

  closeModal = () => {
    let { modalObj } = this.state;
    modalObj.currIsVisible = false;
    this.setState({ modalObj });
  }

  openModal () {
    let { modalObj, listData } = this.state;
    modalObj.currIsVisible = true;
    modalObj.currTitle = '请选择经营区域';
    modalObj.currlistData = listData;
    modalObj.currSelectIndex = this.state.mainTypeSelect;
    modalObj.currCb = this.getMainType;
    this.setState({ modalObj }, () => {
    });
  }

  getMainType = (index) => {
    const { listData } = this.state;
    this.params.zone = listData[index].dictKey;
    this.setState({
      mainTypeSelect: index,
      mainObjectText: listData[index].dictName
    })
    this.closeModal();
  }

  cancelPress () {
    this.setState({ modalVisible: !this.state.modalVisible });
  }

  _changeLog = (index) => {
    console.log('index--888', index)
    ImagePicker.showImagePicker(imgOptions, (response) => {
      if (response.didCancel) {
        console.log('用户取消了选择！');
      }
      else if (response.error) {
        console.log("ImagePicker发生错误：" + response.error);
      }
      else {
        source = { uri: response.uri };
        this._uploadImg(source, index);
      }
    });
  }

  async _uploadImg (imgUrl, index) {
    let uploadImgObj = {
      imgUrl,
      url: API_GENERATE(API.IMG_UPLOAD),
    }
    let responseData = await Upload.uploadImg(uploadImgObj);

    if (responseData) {
      let headObj = await HTTP.GET(API_GENERATE(API.GET_IMG_VIEW), { fileId: responseData.fileId }, null, 30000);
      console.log('图片上次成功之后', headObj)
      if (headObj) {
        this.setState({
          headImg: { uri: headObj.image }
        })
      } else {
        this.setState({
          ls: true
        })
      }
      this._changeImg(responseData.fileId, this.state.imgUrl, index);
    }
  }

  async	_changeImg (fileId, imgUrl, index) {
    if (index == 0 || index) {
      this.state.imgServer[index] = source.uri;
      this.state.fileAddress[index] = fileId;
      console.log('替换', index)
    } else {
      this.state.imgServer.splice(index, 0, source.uri);
      this.state.fileAddress.splice(index, 0, fileId);
      console.log('新增', index)
    }
    this.setState({
      imgServer: this.state.imgServer,
      fileAddress: this.state.fileAddress
    });
  }
  // const {companyId,corpId,companyName} = this.props.navigation.state.params

  _delete (index) {
    this.state.imgServer.splice(index, 1);
    this.state.fileAddress.splice(index, 1);
    this.setState({
      imgServer: this.state.imgServer,
      fileAddress: this.state.fileAddress
    });
  }

  async _submit () {
    const { comments, mainMethodTextCheck } = this.state;
    if (this.request) return;

    if (!mainMethodTextCheck.length) {
      ToastUtil.showWarning('请选择需要关联的经营品类');
      return;
    }
    if (!comments) {
      ToastUtil.showWarning('请输入备注');
      return;
    }

    this.request = true;
    this.params.corpId = this.choice.corpId
    this.params.comments = comments;
    this.params.fileAddress = this.state.fileAddress.join(',');
    this.params.qualificationList = []
    if(this.qualificationList.length>0){
      this.qualificationList.map((item)=>{
        if(item.qualificationAddress){
          this.params.qualificationList.push (item)
        }
      })
    }
    this.setState({ loading: true });
    console.log(this.params)
    const responseData = await HTTP.POST(API_GENERATE(API.UPDATE_CUSTOMER_INFO), this.params);
    if (responseData) {
      this.setState({ loading: false });
      ToastUtil.showSuccess(`提交成功`).then(() => {
        this.request = false;
        navigationSeevice.goBack();
      })
    } else {
      this.setState({ loading: false });
      this.request = false;
    }
  }

  render () {
    let { mainMethodText, mainMethodTextCheck, mainObjectText, comments, modalObj, modalVisible, goodsTreeList, imgServer, loading, searching,showDataList,text } = this.state;
    return (
      <ScrollView>
        <View style={styles.createBox}>
          <View style={[styles.flexRow, styles.selectBox]}>
            <Text style={styles.needed}>*</Text>
            <TouchableOpacity
              style={[styles.flexRow, styles.select]}
              onPress={() => { this.cancelPress() }}
            >
              <View style={styles.flexRow}>
                <Text style={styles.selectTitle}>经营品类</Text>
                <Text style={styles.selectContent}>{mainMethodText || '请关联经营品类'}</Text>
              </View>
              <Image source={selectIcon} style={{ tintColor: '#000' }} />
            </TouchableOpacity>
          </View>
          <View style={[styles.flexRow, styles.selectBox]}>
            <Text style={styles.needed}></Text>
            <TouchableOpacity
              style={[styles.flexRow, styles.select]}
              onPress={() => { this.openModal() }}
            >
              <View style={styles.flexRow}>
                <Text style={styles.selectTitle}>经营区域</Text>
                <Text style={styles.selectContent}>{mainObjectText}</Text>
              </View>
              <Image source={selectIcon} style={{ tintColor: '#000' }} />
            </TouchableOpacity>
          </View>

          <View style={[styles.flexRow, styles.selectBox]}>
            <View style={{ flex: 1 }}>
              <View style={styles.flexRow}>
                <Text style={styles.needed}>*</Text>
                <Text style={styles.selectTitle}>备注</Text>
              </View>
              <TextInput
                style={styles.textInput}
                placeholder={'请输入本次维护内容，限定1000字。'}
                underlineColorAndroid={'transparent'}
                placeholderTextColor={'#B4B8C0'}
                maxLength={1000}
                multiline={true}
                returnKeyType='done'
                blurOnSubmit={true}
                onChangeText={(comments) => this.setState({ comments })}
              />
            </View>
          </View>

          {/* <View style={[styles.flexRow, styles.selectBox]}>
            <Text style={styles.needed}>  </Text>
            <View style={styles.flexRow}>
              <View style={[styles.flexRow]}>
                <Text style={[styles.selectTitle]}>附件</Text>
                <View style={{ flexDirection: 'row', flexWrap: 'wrap', width: 290 * scale, }}>
                  {
                    imgServer.map((item, index) => {
                      return (
                        <View style={{ width: 60 * scale, height: 60 * scale, position: 'relative' }}>
                          <TouchableOpacity onPress={this._delete.bind(this, index)} style={{ zIndex: 10, position: 'absolute', top: 0, right: 0, width: 18 * scale, height: 18 * scale }}>
                            <Image style={styles.close} source={close} />
                          </TouchableOpacity>
                          <TouchableOpacity key={index} onPress={() => { this._changeLog(index) }}>
                            <Image style={{ marginRight: 5 * scale, marginTop: 5 * scale, width: 50 * scale, height: 50 * scale }}
                              source={{ uri: item }}
                            />
                          </TouchableOpacity>
                        </View>
                      )
                    })
                  }
                  <TouchableOpacity onPress={() => { this._changeLog() }}>
                    <Image style={{ marginRight: 5 * scale, width: 60 * scale, height: 60 * scale }}
                      source={defaultImg}
                    />
                  </TouchableOpacity>
                </View>

              </View>
            </View>
          </View> */}
          <View style={styles.qualification}>
            <View style={styles.qualificationTitle}>
              <Text style={{fontSize:12,fontWeight:'bold'}}>企业资质</Text>
              <TouchableOpacity style={styles.quaTitleRight} onPress={()=>{navigationSeevice.navigate('EnterpriseUploadPage', 
                    {
                      companyId:this.companyId,
                      corpId:this.choice.corpId,
                      qualificationList:this.qualificationList,
                      showDataList:this.state.showDataList,
                      type:'save',
                      getImage:(val)=>{
                        console.log(val)
                        this.qualificationList = val.qualificationList
                        this.setState({
                          showDataList:val.showDataList
                        })
                      },
                    }
                  )}}>
                <Image source={require('../../../imgs/plus.png')} style={{width:12,height:12,marginRight:5}} />
                <Text style={{fontSize:12,color:'#0E7FFD'}}>上传资质</Text>
              </TouchableOpacity>
            </View>
            <View style={{marginTop:10*scale}}>
              <Text style={{fontSize:12,color:'#F7B500',lineHeight:18*scale,marginBottom:10*scale}}>
                {text}
              </Text>
            </View>
            <View>
              {showDataList.map((item, index) => {
                return(
                  <View key={index}>
                    {item.uriListUri&&item.uriListUri.length>0?
                      <View>
                      <Text style={{marginBottom:5}}>{item.qualificationTypeText}</Text>
                      <View style={{flexDirection:'row',marginBottom:10*scale,flexWrap:'wrap'}}>
                      {item.uriListUri&&item.uriListUri.map((j,i)=>{
                        return(
                          <TouchableOpacity key={i} 
                            onPress={()=>{
                              if(j.indexOf("pdf")!==-1){
                                navigationSeevice.navigate('ContractPdfPage', {
                                  finalFileId: j.substring(4, j.Length),
                                  title: '附件信息'
                              })
                              }
                              else{
                                modalPicDelCfg.visible = true;
                                modalPicDelCfg.uri = j;
                                this.setState({
                                    ls: true
                                })
                              }
                            }}
                          >
                            {
                                j.indexOf("pdf")!==-1?
                                    <View style={[styles.imageShow,{ flex: 1, flexDirection: 'column', alignItems: 'center', justifyContent: 'center', flexWrap: 'wrap',borderColor:'#0087FF',borderWidth:0.5*scale }]}>
                                        <Text style={{fontSize:12*scale}}>PDF文件</Text>
                                        <Text style={{fontSize:10*scale}}>点击可查看</Text>
                                    </View>
                                    : 
                                    <Image style={styles.imageShow}
                                    source={{ uri: j }}
                                  />
                            }
                            
                          </TouchableOpacity>
                        )
                      })
                      }
                      </View>
                    </View>:null
                    }
                      
                  </View>
                )
                })      
              }
            </View>
          </View>


          <View style={{ flexDirection: 'row', justifyContent: 'center' }}>
            <TouchableOpacity style={styles.button} onPress={() => this._submit()}>
              <Text style={styles.buttonText}>提交</Text>
            </TouchableOpacity>
          </View>
        </View>

        <Modal animationType={"fade"}
          transparent={true}
          onRequestClose={() => { console.log(1) }}
          visible={modalVisible}>
          <View style={styles.back}>
            <TouchableOpacity activeOpacity={1} style={styles.bg} onPress={() => { this.cancelPress() }}>
            </TouchableOpacity>
            <ProductEditing
              searchPress={(searchCode) => {
                this.setState({
                  searching: true
                }, () => {
                  this._getGoodsData(searchCode)
                })
              }}
              data={modalVisible ? goodsTreeList : []}
              searching={searching}
              visible={true}
              rightBtnsList={[{
                btnText: '确认添加',
                btnFun: () => {
                    this.setState({ modalVisible: false, mainMethodText: mainMethodTextCheck.length && mainMethodTextCheck.join(',') });
                    this.getQueInfo()
                }
              }]}
              confirmData={(data) => this._getGoodsCode(data)}
              secondRight={true}
              optionBox={true}
              bannerBtnContent={'* 已存在的产品可直接发起认领，新增审批中无需重复新增'}
            />
          </View>
        </Modal>

        <Common type="modal" demoData={(
          <Common type="listRadio"
            selectIndex={modalObj.currSelectIndex}
            title={modalObj.currTitle}
            listData={modalObj.currlistData || []}
            selectCallBack={modalObj.currCb}
          />
        )}
          isVisible={modalObj.currIsVisible}
          closeCallballFn={this.closeModal}
        />

        {
          loading ?
            <View style={styles.loadingView}>
              <View style={styles.loadedCell}>
                <ActivityIndicator
                  animating={true}
                  color={'#fff'}
                  size="small"
                />
              </View>
            </View> : null
        }
        <ModalPicDelComponent {...modalPicDelCfg} />
      </ScrollView>
    )
  }
}


const styles = StyleSheet.create({
  flexRow: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  createBox: {
    paddingTop: 40 * scale,
    marginLeft: 30 * scale,
    marginRight: 30 * scale,
    marginBottom: 75 * scale
  },
  needed: {
    fontSize: 12 * scale,
    color: '#F80A0A',
    marginRight: 5 * scale,
    width: 5 * scale,
  },
  selectBox: {
    marginBottom: 26 * scale,
  },
  select: {
    flex: 1,
    justifyContent: 'space-between',
    borderBottomWidth: 1,
    borderBottomColor: '#000',
    paddingBottom: 5 * scale,
  },
  selectTitle: {
    fontSize: 12 * scale,
    color: '#000000',
    marginRight: 15 * scale,
    fontWeight:'bold'
  },
  selectContent: {
    flex: 1,
    flexWrap: 'wrap',
    fontSize: 12 * scale,
    color: '#AAB1BF',
  },
  textInput: {
    marginTop: 6 * scale,
    height: 156 * scale,
    width: '100%',
    borderColor: '#000',
    borderWidth: 1 * scale,
    borderRadius: 4 * scale,
    padding: 12 * scale,
    paddingTop: 10 * scale,
    fontSize: 12 * scale,
  },
  statusItemText: {
    fontSize: 12 * scale,
    color: '#34475F'
  },
  button: {
    marginTop: 50 * scale,
    width: 99 * scale,
    height: 39 * scale,
    backgroundColor: '#0E7FFD',
    borderRadius: 15 * scale,
    justifyContent: 'center',
    alignItems: 'center',
  },
  buttonText: {
    fontSize: 14 * scale,
    color: '#fff'
  },
  close: {
    width: 18 * scale,
    height: 18 * scale
  },
  back: {
    width: 375 * scale,
    backgroundColor: 'rgba(0, 0, 0, .3)',
    height: GLOBAL.SCREEN_HEIGHT,
    flex: 1
  },
  bg: {
    width: 375 * scale,
    height: '20%',
  },
  loadedCell: {
    width: 75 * scale,
    height: 75 * scale,
    backgroundColor: 'rgba(0, 0, 0, .5)',
    borderRadius: 7,
    justifyContent: 'center',
    alignItems: 'center',
    marginLeft: 150 * scale,
    marginTop: (Dimensions.get('window').height - 160) / 2,
  },
  loadingView: {
    width: 375 * scale,
    height: Dimensions.get('window').height,
    backgroundColor: 'rgba(0, 0, 0, 0.1)',
    position: 'absolute',
    top: 0
  },
  qualification:{
    paddingLeft:5 * scale,
  },
  qualificationTitle:{
    flexDirection:'row',
    alignItems:'center',
    justifyContent:"space-between"
  },
  quaTitleRight:{
    flexDirection:'row',
    alignItems:'center',
    paddingHorizontal:10 * scale,
    paddingVertical:7 * scale,
    borderWidth:1 * scale,
    borderRadius:50* scale,
    borderColor:'#0E7FFD'
  },
  imageShow:{
    marginRight: 25 * scale, marginTop: 5 * scale, width: 55 * scale, height: 55 * scale
  }
})